﻿/*
    Copyright (c) 2008 - 2009, Carlos Guzmán Álvarez

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
    are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright notice, 
          this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright notice, 
          this list of conditions and the following disclaimer in the documentation and/or 
          other materials provided with the distribution.
        * Neither the name of the author nor the names of its contributors may be used to endorse or 
          promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Threading;
using Framework.Net.Xmpp.Core;
using Framework.Net.Xmpp.InstantMessaging;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using XClient.Infrastructure;
using XClient.Interfaces;
using XClient.ViewModels;
using XClient.Views;

namespace XClient
{
    /// <summary>
    /// Chat View manager
    /// </summary>
    public class ChatViewManager : IChatViewManager
    {
        #region · Sync Object ·

        object SyncObject = new object();

        #endregion

        #region · Fields ·

        private IUnityContainer                 container;
        private IRegionManager                  regionManager;
        private Dispatcher                      dispatcher;
        private IDictionary<string, ChatView>   chatViews;
        private XmppSession                     session;

        #endregion

        #region · Constructors ·

        /// <summary>
        /// Initializes a new instance of the <see cref="ChatViewManager"/> class
        /// </summary>
        /// <param name="container">Unity container</param>
        /// <param name="regionManager">Composite WPF region manager</param>
        public ChatViewManager(IUnityContainer container, IRegionManager regionManager)
        {
            this.container      = container;
            this.regionManager  = regionManager;
            this.chatViews      = new Dictionary<string, ChatView>();
            this.dispatcher     = Dispatcher.CurrentDispatcher;
            this.session        = this.container.Resolve<XmppSession>();

            this.WireEvents();
        }

        #endregion

        #region · Methods ·

        /// <summary>
        /// Opens a new chat view for the given contact jid 
        /// </summary>
        /// <param name="jid">The contact jid</param>
        public void OpenChatView(XmppJid jid)
        {
            this.OpenChatView(jid.BareIdentifier);
        }

        /// <summary>
        /// Opens a new chat view for the given contact jid 
        /// </summary>
        /// <param name="jid">The contact jid</param>
        public void OpenChatView(string jid)
        {
            lock (SyncObject)
            {
                if (!this.container.Resolve<XmppSession>().HasOpenChat(jid))
                {
                    OpenChatView(this.container.Resolve<XmppSession>().CreateChat(jid));
                }
                else
                {
                    if (this.chatViews.ContainsKey(jid))
                    {
                        this.dispatcher.BeginInvoke(
                            DispatcherPriority.Normal,
                            new ThreadStart(delegate
                            {
                                IRegionManager  regionManager   = this.container.Resolve<IRegionManager>();
                                IRegion         region          = regionManager.Regions[RegionNames.SessionRegion];

                                region.Activate(this.chatViews[jid]);
                            }));
                    }
                    else
                    {
                        OpenChatView(this.container.Resolve<XmppSession>().CreateChat(jid));
                    }
                }
            }
        }

        /// <summary>
        /// Opens a new chat view for the given chat instance
        /// </summary>
        /// <param name="chat">A <see cref="XmppChat"/> instance</param>
        public void OpenChatView(XmppChat chat)
        {
            this.dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                new ThreadStart(delegate
                {
                    lock (SyncObject)
                    {
                        IRegionManager  regionManager   = this.container.Resolve<IRegionManager>();
                        IRegion         region          = regionManager.Regions[RegionNames.SessionRegion];
                        ChatViewModel   viewModel       = new ChatViewModel(this.container, chat);
                        ChatView        view            = this.container.Resolve<ChatView>();

                        view.ViewModel = viewModel;
                        this.container.RegisterInstance<ChatViewModel>(viewModel);

                        region.Add(view);
                        region.Activate(view);

                        this.chatViews.Add(chat.Contact.ContactId.BareIdentifier, view);
                    }
                }));
        }

        /// <summary>
        /// Closes the chat view for a given <see cref="XmppChat"/> instance
        /// </summary>
        /// <param name="chat">A <see cref="XmppChat"/> instance</param>
        public void CloseChatView(string jid)
        {
            lock (SyncObject)
            {
                IRegionManager  regionManager   = this.container.Resolve<IRegionManager>();
                IRegion         region          = regionManager.Regions[RegionNames.SessionRegion];
                ChatView        chatView        = this.chatViews[jid];

                region.Remove(this.chatViews[jid]);
                this.chatViews.Remove(jid);
            }
        }

        #endregion

        #region · Private Methods ·

        private void WireEvents()
        {
            this.session.StateChanged           += new EventHandler<XmppSessionStateChangedEventArgs>(OnSessionStateChanged);
            this.session.ChatMessageReceived    += new EventHandler<XmppMessageReceivedEventArgs>(OnChatMessageReceived);
        }

        private void UnwireEvents()
        {
            this.session.ChatMessageReceived    -= new EventHandler<XmppMessageReceivedEventArgs>(OnChatMessageReceived);
        }

        #endregion

        #region · Event Handlers ·

        private void OnSessionStateChanged(object sender, XmppSessionStateChangedEventArgs e)
        {
            if (e.NewState == XmppSessionState.LoggingOut)
            {
                lock (SyncObject)
                {
                    IRegionManager  regionManager   = this.container.Resolve<IRegionManager>();
                    IRegion         region          = regionManager.Regions[RegionNames.SessionRegion];
                    List<string>    removedViews    = new List<string>();
                    IEnumerator<KeyValuePair<string, ChatView>> enumerator = this.chatViews.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        region.Remove(enumerator.Current.Value);
                        removedViews.Add(enumerator.Current.Key);
                    }

                    foreach (string jid in removedViews)
                    {
                        this.chatViews.Remove(jid);
                    }
                }

                this.UnwireEvents();
            }
        }

        private void OnChatMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
            this.OpenChatView(e.Message.From);
        }

        #endregion
    }
}
